<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="roomId" label="名称">
                  <a-input
                    v-model="formModel.name"
                    placeholder="请输入房间名称或者课程名称"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item field="nickname" label="上课时间">
                  <a-range-picker
                    @change="onChangedatas"
                    v-model="datess"
                    style="width: 254px; marginbottom: 20px"
                  ></a-range-picker>
                </a-form-item>
              </a-col>

              <a-col :span="5">
                <a-space :size="18">
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="addedit">
              <template #icon>
                <icon-plus />
              </template>
              新增
            </a-button>

            <a-button @click="openUpload"> 批量导入 </a-button>
            <a-button status="danger" @click="pldel"> 批量删除 </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        ref="userList"
        row-key="timetableId"
        v-model:selectedKeys="timetableId"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :row-selection="rowSelection"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #startTime="{ record }">
          <a-space :size="18">
            {{ record.startTime }} - {{ record.endTime }}
          </a-space>
        </template>
        <template #option="{ record }">
          <a-space :size="18">
            <a-button @click="openEdit(record)" type="primary"> 编辑 </a-button>
            <a-button
              status="danger"
              @click="openDelete(record)"
              v-if="record.username != 'admin'"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <a-modal
      class="df"
      v-model:visible="uploadShow"
      @cancel="uploadCancel"
      :on-before-ok="uploadCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 导入课表 </template>
      <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item label="选择日期" field="dates">
            <a-range-picker
              v-model="uploadForm.dates"
              @change="onChangedata"
              style="width: 254px; marginbottom: 20px"
          /></a-form-item>
          <a-form-item field="file" label="文件">
            <a-upload
              class="upload_box"
              @change="onChange"
              accept=".xls,.xlsx"
              ref="uploadRef"
              :auto-upload="false"
              :limit="1"
            >
              <template #upload-button>
                <a-space>
                  <a-button type="primary">选择附件</a-button>
                  <a-button @click.stop="downloadTemplate">下载模板</a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
      width="500px"
    >
      <template #title> 课表 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row>
          <a-col>
            <a-form-item field="courseName" label="课程名称">
              <a-input
                v-model="addForm.courseName"
                size="large"
                placeholder="请输入课程名称"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col>
            <a-form-item field="roomId" label="房间名称">
              <a-select
                :options="roomData"
                v-model="addForm.roomId"
                :style="{ width: '320px' }"
                placeholder="请选择房间名称"
                :field-names="rolesFieldsd"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-item field="timeId" label="上课时间">
              <a-select
                :options="roomtime"
                v-model="addForm.timeId"
                :style="{ width: '320px' }"
                placeholder="请选择上课时间"
                :field-names="rolesFieldsds"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-item field="dates" label="上课日期">
              <a-date-picker
                style="width: 200px"
                @change="onChangess"
                v-model="addForm.dates"
              />
              <!-- <a-range-picker
                v-model="addForm.dates"
                style="width: 360px; margin: 0 24px 24px 0"
                show-time
                format="YYYY-MM-DD HH:mm"
                @change="onChangess"
              /> -->
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import useLoading from '@/hooks/loading';

  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';

  import {
    downloadTemplate,
    importClass,
    timetableList,
    timetableRemove,
    timetableSave,
    roomList,
    addSave,
    appointmentTime,
  } from '@/api/classbk';
  const rolesFieldsd = {
    value: 'roomId',
    label: 'roomName',
  };
  const rolesFieldsds = {
    value: 'timeId',
    label: 'time',
  };
  const { loading, setLoading } = useLoading(true);
  const timetableId = ref([]);
  const roomData = ref([]);
  const roomtime = ref([]);
  const roomtimefn = () => {
    appointmentTime().then((res) => {
      roomtime.value = res.data.map((item) => ({
        timeId: item.timeId,
        time: `${item.startTime}-${item.endTime}`,
      }));
      console.log('获取到房间时间', roomtime.value);
    });
  };
  roomtimefn();
  const roomDatafn = () => {
    roomList().then((res) => {
      roomData.value = res.data;
      console.log('获取到房间数据', roomData.value);
    });
  };
  roomDatafn();
  const pldel = () => {
    if (timetableId.value.length == 0) {
      Modal.confirm({
        title: '提示',
        content: '请先选中要删除的课程？',
      });
    } else {
      Modal.confirm({
        title: '提示',
        content: '确定进行删除吗？',
        onOk() {
          Promise.all(
            timetableId.value.map((timetableId) => {
              return timetableRemove({ timetableId }).then((res) => {
                if (res.code == '200') {
                  return true; // 标记删除成功
                } else {
                  fetchData();
                  throw new Error('删除失败');
                }
              });
            })
          )
            .then((results) => {
              // 检查所有结果是否都为 true，表示删除成功
              if (results.every((result) => result === true)) {
                // 如果所有删除成功，显示成功提示
                Message.success({
                  content: '删除成功',
                });

                // 然后重新获取数据
                fetchData();
              }
            })
            .catch((err) => {
              fetchData();
              console.error('删除失败:', err);
            });
        },
      });
    }
    console.log('执行了飘了删除', timetableId.value);
  };
  const dates = ref([]);
  const datess = ref([]);
  const onChangess = (value) => {
    console.log('ddd的', value);
    // addForm.value.startDate = value[0];
    // addForm.value.endDate = value[1];
  };
  const onChangedatas = (value) => {
    formModel.value.startDate = value[0];
    formModel.value.endDate = value[1];

    console.log(formModel.endDate);
  };
  const onChangedata = (value) => {
    uploadForm.dates = value;
    dates.value = value;

    // uploadModel.value
    //   .validateField('dates')
    //   .then(() => {
    //     console.log('验证通过');
    //   })
    //   .catch((errorInfo: any) => {
    //     console.log('验证失败', errorInfo);
    //   });
    console.log(formModel.endDate);
  };
  const generateDataModel = () => {
    return {
      dates: [],
      startDate: '',
      endDate: '',
    };
  };
  const onChange = (fileList) => {
    if (fileList && fileList.length > 0) {
      uploadForm.value.file = fileList[0].file;
    } else {
      uploadForm.value.file = null;
    }
  };

  const rules = reactive({
    timetableId: [
      {
        required: true,
        message: '请输入用户名',
      },
    ],
    courseName: [
      {
        required: true,
        message: '请输入课程名称',
      },
    ],
    roomId: [
      {
        required: true,
        message: '请选择房间',
      },
    ],
    timeId: [
      {
        required: true,
        message: '请选择上课时间',
      },
    ],
    dates: [
      {
        required: true,
        message: '请选择上课日期',
      },
    ],
  });
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const updatetime = ref(['', '']);

  const openEdit = (item) => {
    addForm.value.timetableId = item.timetableId;
    addForm.value.roomId = item.roomId;
    addForm.value.courseName = item.courseName;
    // updatetime.value[0] = item.date + ' ' + item.startTime + ':00';
    // updatetime.value[1] = item.date + ' ' + item.endTime + ':00';
    // updatetime.value[0] = item.date + ' ' + item.startTime;
    // updatetime.value[1] = item.date + ' ' + item.endTime;
    addForm.value.dates = item.date;
    console.log('item', item);
    const time = `${item.startTime}-${item.endTime}`;
    //
    const result = roomtime.value.find((item) => item.time == time);
    console.log('当前tim', result);

    if (result != undefined) {
      addForm.value.timeId = result.timeId;
    }

    addShow.value = true;

    // console.log('ss', rules.username[0].required);
  };
  const addedit = (item) => {
    addForm.value = [];
    addShow.value = true;

    // console.log('ss', rules.username[0].required);
  };

  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        timetableRemove({
          timetableId: item.timetableId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            fetchData();
          }
        });
      },
    });
  };

  const userIds = ref([]);

  const generateUploadModel = () => {
    return {
      file: null,
      deptId: '',

      effectiveTime: '',
      majorIds: '',
      majorIdsArr: [],
    };
  };

  const uploadRules = {
    dates: [
      {
        required: true,
        message: '请选择日期',
      },
    ],
    file: [
      {
        required: true,
        message: '请选择附件',
      },
    ],
  };
  const uploadForm = ref(generateUploadModel());
  const uploadShow = ref(false);
  const uploadModel = ref();
  const openUpload = () => {
    uploadForm.value = generateDataModel();
    uploadShow.value = true;
  };

  const uploadCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          let formData = new FormData();
          formData.append('startDate', dates.value[0]);
          formData.append('endDate', dates.value[1]);
          formData.append('file', uploadForm.value.file);
          importClass(formData).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '新增成功',
              });
              reset();
              done(true);
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadCancel = () => {
    uploadShow.value = false;
  };

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '日期',
      dataIndex: 'date',
    },
    // {
    //   title: '',
    //   dataIndex: 'endTime',
    // },
    {
      title: '上课时间',
      dataIndex: 'startTime',
      slotName: 'startTime',
    },

    {
      title: '所用教室',
      dataIndex: 'roomName',
      align: 'center',
    },
    {
      title: '课程名称',
      dataIndex: 'courseName',
      align: 'center',
    },

    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const generateFormModel = () => {
    return {
      startDate: '',
      endDate: '',
      roomId: '',
    };
  };

  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      timetableList(data).then((res) => {
        let list = res.data.list || [];
        // list.map((item) => {
        //   item.disabled = item.isLocking == 1 ? false : true;
        // });
        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.current;

        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  const reset = () => {
    datess.value = [];
    formModel.value = generateFormModel();
    fetchData();
  };
  fetchData();
  const addModel = ref();

  const handleCheck = (done) => {
    console.log('修改中');

    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.timetableId) {
            const result = roomtime.value.find(
              (item) => item.timeId == addForm.value.timeId
            );
            timetableSave({
              timetableId: addForm.value.timetableId,
              // startTime: addForm.value.dates[0],
              // endTime: addForm.value.dates[1],
              // roomId: addForm.value.roomId,
              // courseName: addForm.value.courseName,
              date: addForm.value.dates,
              time: result.time,
              // startTime: addForm.value.dates[0],
              // endTime: addForm.value.dates[1],
              roomId: addForm.value.roomId,
              courseName: addForm.value.courseName,
            }).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '编辑成功!',
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          } else {
            const result = roomtime.value.find(
              (item) => item.timeId == addForm.value.timeId
            );

            addSave({
              date: addForm.value.dates,
              time: result.time,
              // startTime: addForm.value.dates[0],
              // endTime: addForm.value.dates[1],
              roomId: addForm.value.roomId,
              courseName: addForm.value.courseName,
            }).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '新增成功',
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };
</script>
